package leetcode.method.dynamic_programming;

public class Program221MaximalSquare {

    public Program221MaximalSquare() {

    }
    public int maximalSquare(char[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        if(m == 0 || n ==0) {
            return 0;
        }

        int[][] dp = new int[m][n];

        int max = 0;
        for (int i = 0; i < m; i++) {
            dp[i][0] = matrix[i][0] - '0';
            if (max != 1) {
                max = dp[i][0];
            }
        }
        for (int j = 1; j < n; j++) {
            dp[0][j] = matrix[0][j] - '0';
            if (max != 1) {
                max = dp[0][j];
            }
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == '0') {
                    dp[i][j] = 0;
                } else {
                    dp[i][j]  = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
                }
                max = Math.max(max, dp[i][j]);
            }
        }

        return max * max;
    }

    public static void main(String[] args) {
        Program221MaximalSquare myStack = new Program221MaximalSquare();
        char[][] matrix = {
                {'1','0','1','0','0'}
                ,{'1','0','1','1','1'}
                ,{'1','1','1','1','1'}
                ,{'1','0','0','1','0'}
        };
        System.out.println(myStack.maximalSquare(matrix));
        char[][] matrix1 = {
                {'0','1'}
                ,{'1','0'}
        };
        System.out.println(myStack.maximalSquare(matrix1));
    }
}
